//
// Created by changlei on 2022/4/29.
//

import Foundation
import UIKit


/// 获取[UIView]所在的[UIViewController]
public extension UIView {
    var viewController: UIViewController? {
        var next = next
        repeat {
            if let next = next, next.isKind(of: UIViewController.self) {
                return (next as! UIViewController)
            }
            next = next?.next
        } while (next != nil)
        return nil
    }

    func findSubview<T: UIView>(_ class: T.Type) -> T? {
        var targetView: T?

        func visitor(_ view: UIView) {
            for item in view.subviews {
                if item is T {
                    targetView = (item as! T)
                    return
                } else {
                    visitor(item)
                }
            }
        }

        visitor(self)

        return targetView
    }
}

extension UIViewController {
    func canGoBack(_ completion: @escaping (_ canGoBack: Bool) -> Void) {
        let viewControllers: [UIViewController]?
        if let navigationController = navigationController {
            viewControllers = navigationController.viewControllers
        } else {
            viewControllers = presentedViewController?.children
        }

        func animateCompletion() {
            completion((viewControllers?.firstIndex(of: self) ?? 0) > 0)
        }

        guard let transitionCoordinator = transitionCoordinator else {
            animateCompletion()
            return
        }

        transitionCoordinator.animateAlongsideTransition(in: view, animation: nil) { context in
            animateCompletion()
        }
    }
}